{% extends "V.html" %}

{% block head %}

<script type="text/javascript" src="/static/matrix/js/layer/layer.js"></script>
<script type="text/javascript" src="/static/matrix/js/dataBase.js"></script>
<script type="text/javascript" src="/static/matrix/js/preview/WdatePicker.js"></script>
<script type="text/javascript">
	
	$(document).ready(function(){
		loadpermission();
		{% if perms.Matrix.auth_get_grolist_and_perm %}
		loadTable(1);
		{% else %}
		$('#myTabContent').html('对不起,非管理员没有此项功能权限').css('text-align','center');
		{% endif%}
	});

	$("#reset").button("reset");

	function loadpermission(){
		$.ajax({
			type:'POST',
			url:'/auth_data/get_groupslist_and_permission/',
			dataType:'json',
			success:function(val){
				console.log(val);
				for(var i=0;i<val.all_permissionslist.length;i++){
					$("#usrpermissionlist").append("<option>"+val.all_permissionslist[i]+"</option>")
				}
				for(var j=0;j<val.all_groupslist.length;j++){
					$("#groupslist").append("<option>"+val.all_groupslist[j]+"</option>")
				}

			}
		})
	};


	// 以下是创建权限限制
	function adduser(){
		var parameters = ['username','password','confirmpassword','first_name','email','usrpermissionlist','groupslist','is_active','is_staff','is_superuser']
		// var parameters = ['username','password','confirmpassword','first_name','email']
		var username =$("#username").val()
		var password =$("#password").val()
		var confirmpassword =$("#confirmpassword").val()
		var username = $("#username").val()
		var usrpermissionlist =$("#usrpermissionlist option:selected").text()
		var groupslist =$("#groupslist option:selected").text()


		if($("[name='is_active']").attr("checked")=='checked'){
			$("[name='is_active']").val("True")
			// console.log($("#is_active").val());
		}else{
			$("[name='is_active']").val("False")
			// console.log($("#is_active").val());
		}

		if($("[name='is_staff']").attr("checked")=='checked'){
			$("[name='is_staff']").val("True")
			// console.log($("#is_staff").val());
		}else{
			$("[name='is_staff']").val("False")
			// console.log($("#is_staff").val());
		}
		if($("[name='is_superuser']").attr("checked")=='checked'){
			$("[name='is_superuser']").val("True")
			// console.log($("#is_superuser").val());
		}else{
			$("[name='is_superuser']").val("False")
			// console.log($("#is_superuser").val());
		}
		data=""
		$.each(parameters,function(){
			data+=this+'='+$("#"+this).val()+'&';
		});
		
		// console.log(data);
		if(username == ""){
			$("#add_success").html('用户名不能为空').css('color','red');
		}else if(password == ""){
			$("#add_success").html('密码不能为空').css('color','red');
		}else if( password.length < 8){
			$("#add_success").html('密码长度不能少于8位').css('color','red');
		}else if(password == confirmpassword){
			// var data = {'name':name,'password':password,"confirmpassword":confirmpassword};
			// var url = '/authmanagement/'+'add_test/'
			var url = '/auth_data/useradd/'
			console.log(data);
			console.log(url);
			//url传url+动作，data传输具体数据
			// data = 'username=biyingyong&password=yozo.com.3.&is_active=on&is_staff=on&is_superuser=on'
			$.ajax({
				type:'POST',
				url:url,
				dataType:'text',
				data:data,
				success:function(val){
					if(val=='1'){
						$("#add_success").html("用户创建成功,<a href='#auth'>点击查看</a>").css('color','green');
						$("#reset").button("reset");
					}else{
						$("#add_success").html("创建失败，用户已存在").css('color','red');
					};
					$("input select").val("");
					console.log(val);
				},error:function(){
					alert('no');
				}
			});
		}else if(usrpermissionlist == ""){
			$("#add_success").html('用户权限不能为空').css('color','red');
		}else if(groupslist == ""){
			$("#add_success").html('用户属组不能为空').css('color','red');
		}else{
			$("#add_success").html('密码不一致，请重新输入密码').css('color','red');
			$("#confirmpassword").val("");
		}
	};


	function getuserlist(){
		$.ajax({
				type:'POST',
				url:'/auth_data/userinfolist/',
				dataType:'json',
				data:{'page':1,"num":15},
				success:function(val){
					console.log(val);
					loadTable(val);
				},error:function(){
					alert('no');
				}
		})
	};



	function loadTable(val){
		 $("#dataFrom").find("input[name='page']").val(val);
		 $("#dataTab").dataTable({
				title:'用户权限列表',
				columns:[
				{key:'id',check:true,checkAll:true,width:'1%',align:'center'},
				{key:'username',name:'用户名',width:'3%',align:'center'},
				{key:'email',name:'邮箱',width:'3%',align:'center'},
				{key:'first_name',name:'姓名',width:'3%',align:'center'},
				{key:'is_active',name:'是否有效',width:'3%',align:'center'},
				{key:'is_staff',name:'职员状态',width:'3%',align:'center'},
				{key:'is_superuser',name:'超级用户',width:'3%',align:'center'},
				{key:'date_joined',name:'创建时间',width:'5%',align:'center'},
				{key:'groups',name:'所属用户组',width:'10%',align:'center'},
				{key:'get_all_permissions',name:'所具有权限(自定义权限)',width:'20%',align:'center'}],
				formid:'dataFrom',
				loadAfter:tab_trOnclick,
		});
	};

	function keyEnter(event){
		 var e = event || window.event || arguments.callee.caller.arguments[0];
		 if(e && e.keyCode==13){ // enter 键
             loadTable(1);
			return false;
          }

	}

	function addDialog(){
		var addTableHtml=$("#addTable").clone();
		var parameters=['id','username','email','first_name','permissionlist','addgroupslist','is_active','is_staff','is_superuser'];
		// var inputStatus=addTableHtml.find("select[name='status']");
  //     		inputStatus.attr("id","status");
  //     		if(arguments[4]){
  //     			inputStatus.find("option[name='"+arguments[2]+"']").attr("selected",true);
  //     		}


		var inputGroupList=addTableHtml.find("select[name='addgroupslist']");
		var inputUserPermissionList=addTableHtml.find("select[name='permissionlist']");
		var UserPermission_selected=arguments[4];
		var Group_selected=arguments[5];
			inputGroupList.attr("id","addgroupslist");
			inputUserPermissionList.attr("id","permissionlist");
            $.ajax({
              type:'POST',
              url:'/auth_data/get_groupslist_and_permission',
              data:"hostop={{ true_name }}",
              cache:false,
              dataType:'json',
              success:function(ret){
              	console.log(ret)
                if(!ret){
                  layer.alert("数据异常01！");
                }else{
                  var addgroupslist=ret.all_groupslist;
                  var permissionslist=ret.all_permissionslist;

                  for(var i=0;i<addgroupslist.length;i++){
                    if("undefined" == typeof Group_selected||addgroupslist[i]!=Group_selected){
                      $("#addgroupslist").append($('<option value="'+addgroupslist[i]+'" name="'+addgroupslist[i]+'"></option>').html(addgroupslist[i]));
                    }else{
                      $("#addgroupslist").append($('<option selected="selected" value="'+addgroupslist[i]+'" name="'+addgroupslist[i]+'"></option>').html(addgroupslist[i]));
                    }
                  }

                  for(var i=0;i<permissionslist.length;i++){
                    if("undefined" == typeof UserPermission_selected||UserPermission_selected.indexOf(permissionlist[i])<0){
                      $("#permissionlist").append($('<option value="'+permissionslist[i]+'" name="'+permissionslist[i]+'"></option>').html(permissionslist[i]));
                    }else{
                      $("#permissionlist").append($('<option selected="selected" value="'+permissionslist[i]+'" name="'+permissionslist[i]+'"></option>').html(permissionslist[i]));
                    }
                  }

                }
              },error:function(){
                layer.alert("未知异常02！");
              }
            });

    if(arguments[0]){
      var buttonValue="更新";
      $.each(arguments,function(num,val){
        var inputName=addTableHtml.find("input[name='"+parameters[num]+"']");
        if(parameters[num]=='sid'){
          inputName.attr("readonly","readonly");
        }
          inputName.attr("id",parameters[num]);
          inputName.attr("value",val);
      });
    }else{
      var buttonValue="添加";
      $.each(parameters,function(){
        var inputName=addTableHtml.find("input[name='"+this+"']");
          inputName.attr("id",this);
      });
    }

		layer.open({
					title:'编辑信息',
				 	type: 1,
					shift:2,
					skin: 'layui-layer-rim', //加上边框
					area: ['30%', '60%'], //宽高
					content:addTableHtml.html(),
					btn:[buttonValue,'取消'],
					yes:function(index){

						var ret='';
						$.each(parameters,function(){
							ret+=this+'='+$("#"+this).val()+'&';
						});
						ret+="hostop={{ true_name }}"
						// 测试输出
						console.log(ret)
						$.ajax({
							type:'POST',
							url:'/base_data/baseinfo_editFun',
							data:ret,
							dataType:'text',
							success:function(val){
								layer.close(index);
								if(val=='1'){
									loadTable(1);
								}else{
									layer.alert("操作失败，请补全红色必填字体");
								}
							},error:function(){
								layer.close(index);
								layer.alert("操作失败");
							}
						});

					}
			});
	}
	/**
	行添加双击事件
	**/

	function tab_trOnclick(){
		var trs=$("#dataFrom_table tbody tr");
		for(var i=0;i<trs.length;i++){
			$(trs[i]).on("dblclick",function(){
				var tr=$(this);
				var tds=tr.find("td");
				var cloudurl=tr.find("a");
				var id=$(tds[0]).find("input").val();
				addDialog(id,$(tds[1]).text(),$(tds[2]).text(),$(tds[3]).text(),$(tds[4]).text(),$(tds[5]).text(),$(tds[6]).text(),$(tds[7]).text(),$(tds[8]).text());
			});
		}
	}



	/**
	删除功能
	**/
	function userdel(){
		var inputChecks=$("input:checkbox[name='dataFrom_check']:checked");
		if(inputChecks.length==0){
			layer.alert('请选中删除项！');
			return;
		}
		layer.confirm('确认删除?', {icon: 2, title:'提示'},function(index){
			var orders='';
			for(var i=0;i<inputChecks.length;i++){
				orders+=inputChecks[i].value;
				if(i!=inputChecks.length-1){
					orders+=',';
				}
			}
			$.ajax({
				type:'POST',
				url:'/auth_data/userdel/',
				dataType:'text',
				data:'id='+orders,
				success:function(text){
				       layer.close(index);
				       if(text=='1'){
				       	loadTable(1);
				       }else{
				       	layer.alert('操作失败');
				       }
				},error:function(){
					layer.close(index);
					layer.alert('操作失败');
				}
			});
		});

	}



</script>

{% endblock %}

{% block content %}
<!-- 承上连接V.html：content+content-header -->

  <div class="container-fluid">
    <div class="row-fluid">
      <div class="span12">
		<ul id="myTab" class="nav nav-tabs">
		   <li class="active"><a href="#adduser" data-toggle="tab" class="btn btn-info">创建用户</a></li>
		   <li><a href="#auth" data-toggle="tab" class="btn btn-info" onclick="loadTable(1)">用户权限列表</a></li>
		</ul>
		
		<div id="myTabContent" class="tab-content">
		   <div class="tab-pane fade in active" id="adduser">
		   	<div id="add_success"></div>
			<div class="widget-box">
		        <div class="widget-title"> <span class="icon"> <i class="icon-align-justify"></i> </span><h5>创建用户</h5></div>
		        <div class="widget-content nopadding">
		          <form action="" method="" class="form-horizontal">
		            	<div class="control-group">
			              <label class="control-label" style="color:red">**用户名：</label>
			              <div class="controls ">
			                <input type="text" class="col-md-5" id='username' placeholder="输入用户名" />
			              </div>
			            </div>
			            <div class="control-group">
			              <label class="control-label" style="color:red">**登陆密码：</label>
			              <div class="controls">
			                <input type="password" class="col-md-5" id='password' placeholder="输入密码" />
			              </div>
			            </div>
			            <div class="control-group">
			              <label class="control-label" style="color:red">**密码确认：</label>
			              <div class="controls">
			                <input type="password"  class="col-md-5" id='confirmpassword' placeholder="密码确认"  />
			              </div>
			            </div>
			            <hr>
			            <div class="control-group">
			              <label class="control-label">用户姓名：</label>
			              <div class="controls">
			                <input type="text"  class="col-md-5" id='first_name' placeholder="用户姓名"  />
			              </div>
			            </div>
			            <div class="control-group">
			              <label class="control-label">邮箱地址：</label>
			              <div class="controls">
			                <input type="email"  class="col-md-5" id='email' placeholder="邮箱"  />
			              </div>
			            </div>
			            <hr>
			        <div class="control-group">
		              <label class="control-label" style="color:red">**权限列表</label>
		              <div class="controls">
		                <select multiple id="usrpermissionlist" size=20></select>
		              </div>
		            </div>
		            <hr>
		            <div class="control-group">
		              <label class="control-label" style="color:red">**用户组</label>
		              <div class="controls">
		                <select multiple id='groupslist' size=6></select>
		              </div>
		            </div>
		            <div class="control-group">
		              <label class="control-label">权限</label>
		              <div class="controls">
		                <label><input type="checkbox" id="is_active" name="is_active" />启用普通用户</label>
		                <label><input type="checkbox" id="is_staff" name="is_staff" />启动登陆后台</label>
		                <label><input type="checkbox" id="is_superuser" name="is_superuser" />启用超级用户</label>
		              </div>
		            </div>
		            <div class="control-group">
			            <div class="form-actions" style="float:right">
			            	<button type="submit" class="btn btn-warning" id='reset'>重置</button>
			              	<button type="button" class="btn btn-success" onclick="adduser();">创建</button>
			            </div>
		            </div>
		          </form>
		        </div>
		      </div>
		   </div>
		   <div class="tab-pane fade" id="auth">
		   	 <form action="/auth_data/userinfolist/" id="dataFrom" onSubmit="return false">
		    	<input type="hidden" id="page" name="page" value="1"/>
		        <input type="hidden" id="num" name="num" value="15"/>
	   			<div>
					<input class="btn btn-danger" type="button" name="deleteButton" value="删除" onclick="userdel();" style="float:left;"/>
		    		<input type="text" name="tj" placeholder="请输入关键字,回车查询" id="tj" style="background-color: white; float:right" onKeydown="keyEnter();"/>
				</div>
				<div id="dataTab"></div>
		   	</form>
		   </div>
		  </div>
		   </div>
		</div>
   	   </div>
   </div>
  </div>

<!-- 	<div class="widget-box">
          <div class="widget-title">
            <ul class="nav nav-tabs">
              <li class="active"><a data-toggle="tab" href="#adduser">创建用户</a></li>
              <li><a data-toggle="tab" href="#auth" onclick="loadTable(1)">用户权限列表</a></li>
            </ul>
          </div>
          <div id="myTabContent" class="widget-content tab-content">
            <div id="adduser" class="tab-pane active">11111</div>
            <div id="auth" class="tab-pane">2222</div>
          </div>
      </div> -->



    <div id="addTable" style="display:none;">
  		<center>
        	 <table border="0" style="color:#000;">
        	    <tr style="display:none;">
                	<td style="text-align:right;"><span style="position:relative; top:-5px;"></span></td>
                    <td><input type="text" name="id"/></td>
                </tr>
                <tr>
                	<td style="text-align:right;"><span style="position:relative; top:-5px;">用户名：</span></td>
                    <td><input type="text" name="username"/></td>
                </tr>
                <tr>
                	<td style="text-align:right;"><span style="position:relative; top:-5px;">邮箱地址：</span></td>
                    <td><input type="email" name="email"/></td>
                </tr>
                <tr>
                	<td style="text-align:right;"><span style="position:relative; top:-5px;">用户姓名：</span></td>
                    <td><input type="text" name="first_name"/></td>
                </tr>
                <tr>
                	<td style="text-align:right;"><span style="position:relative; top:-5px;">权限列表：</span></td>
                    <!-- <td><input type="text" name="phonecall"/></td> -->
                    <td><select multiple name='permissionlist' size=20></select></td>

                </tr>
                <tr>
                	<td style="text-align:right;"><span style="position:relative; top:-5px;">用户属组：</span></td>
                    <!-- <td><input type="text" name="memo"/></td> -->
                    <td><select multiple name='addgroupslist' size=6></select></td>
                </tr>
                <tr>
                  <td style="text-align:right;"><span style="position:relative; top:-5px;">权限：</span></td>
                    <td>
                    	<label><input type="checkbox" id="is_active" name="is_active" />启用普通用户</label>
		                <label><input type="checkbox" id="is_staff" name="is_staff" />启动登陆后台</label>
		                <label><input type="checkbox" id="is_superuser" name="is_superuser" />启用超级用户</label>
		            </td>
                </tr>
            </table>
         </center>
   </div>


{% endblock %}